package stockin

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StockinRemoveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStockinRemoveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *StockinRemoveLogic {
	return &StockinRemoveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StockinRemoveLogic) StockinRemove(req *types.StockInRequest) (resp *types.BaseResponse, err error) {
	resp = new(types.BaseResponse)
	//1.查询入库单详细原料
	details, err := l.svcCtx.StockInDetailModel.FindByPage(l.ctx, fmt.Sprintf(" where stock_id=%d", req.Id))
	switch err {
	case nil:
	case model.ErrNotFound:
		fmt.Printf("[Info[入库单[%d]没有详细原料\n", req.Id)
	default:
		fmt.Printf("[Error]查询入库单[%d]详细原料:%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.删除入库单详细原料
	for _, detail := range details {
		err = l.svcCtx.StockInDetailModel.Delete(l.ctx, detail.Id)
		if err != nil {
			fmt.Printf("[Error]查询入库单[%d]详细原料[%d]:%s\n", req.Id, detail.Id, err.Error())
			resp.Code = http.StatusInternalServerError
			resp.Msg = "服务内部错误"
			return resp, nil
		}
	}

	//3.删除入库单
	err = l.svcCtx.StockInModel.Delete(l.ctx, req.Id)
	if err != nil {
		fmt.Printf("[Error]查询入库单[%d]:%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
